module repository.menu;

import database.mydb;
import models.menu;

/** 
 * 获取菜单列表
 * Returns: Menu[]
 */
Menu[] getAllMenus()
{
    return dbsess.createQuery("FROM Menu ORDER BY id").list!Menu();
}

/** 
 * 通过菜单id获取菜单
 * Params:
 *   menuId = long
 * Returns: Menu
 */
Menu getMenuById(long menuId)
{
    Menu menu = dbsess.createQuery("FROM Menu WHERE id=:menuId")
        .setParameter("menuId", menuId).uniqueResult!Menu();

    return menu;
}

/** 
 * 通过ids获取菜单列表
 * Params:
 *   menuIds = long[]
 * Returns: Menu[]
 */
Menu[] getMenuListByIds(long[] menuIds)
{
    import std.array : join, array;
    import std.algorithm : map;
    import std.conv : text;
    import std.format : format;

    // import std.algorithm : each;
    // string[] menuStrIds;
    // menuIds.each!(x => menuStrIds ~= text(x));
    // return dbsess.createQuery("FROM Menu WHERE id IN (" ~ join(menuStrIds, ",") ~ ")").list!Menu();

    string[] menuStrIds = map!(x => text(x))(menuIds).array();
    string sql = format("FROM Menu WHERE id IN (%s)", join(menuStrIds, ","));

    return dbsess.createQuery(sql).list!Menu();
}

/** 
 * 添加菜单
 * Params:
 *   newMenu = Menu
 * Returns: bool
 */
bool doAddMenu(Menu newMenu)
{
    auto res = dbsess.save(newMenu);
    if (!res.hasValue || res <= 0)
    {
        return false;
    }
    return true;
}

/** 
 * 修改菜单
 * Params:
 *   newMenu = Menu
 * Returns: bool
 */
bool doUpdateMenu(long menuId, Menu newMenu)
{
    Menu oldMenu = dbsess.createQuery("FROM Menu WHERE id=:menuId")
        .setParameter("menuId", menuId).uniqueResult!Menu();
    if (oldMenu is null)
    {
        return false;
    }
    oldMenu.parentId = newMenu.parentId;
    oldMenu.name = newMenu.name;
    oldMenu.type = newMenu.type;
    oldMenu.routePath = newMenu.routePath;
    oldMenu.component = newMenu.component;
    oldMenu.perm = newMenu.perm;
    oldMenu.visible = newMenu.visible;
    oldMenu.sort = newMenu.sort;
    oldMenu.icon = newMenu.icon;
    oldMenu.redirect = newMenu.redirect;
    oldMenu.updateTime = newMenu.updateTime;

    dbsess.update(oldMenu);
    return true;
}

/** 
 * 删除菜单
 * Params:
 *   menuId = long
 * Returns: bool
 */
bool deleteMenuById(long menuId)
{
    Menu menu = dbsess.createQuery("FROM Menu WHERE id=:menuId")
        .setParameter("menuId", menuId).uniqueResult!Menu();

    if (menu is null)
    {
        return false;
    }
    dbsess.remove(menu);
    return true;
}
